// pages/carryBox/carryBox.js
var util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderStatus: "",
    orderAddressId: "",
    box_type_id: "",
    numInputisabled:"true",
    userInfo: {},
    items: [
      { name: 'no-box', value: '不需要带箱子', checked: 'true' },
    ],
    minusStatuses: ['disabled', 'disabled', 'normal', 'normal', 'disabled'],
    // numInputStatuses: ['disabled', 'disabled'],
    carts: [
      { useBox: '0', size: 'big', name: '大号保温箱子', num: '0', selected: true },
      { useBox: '0', size: 'small', name: '中号保温箱子', num: '0', selected: false }
    ],
    box_small: [
      { num: '1', price: '198.0', sum: '198.0', selected: false },
    ]

  },
  // 点击不需要带箱子  
  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value);
    var carts = this.data.carts;
    console.log(e.detail.value.length);
    if (e.detail.value.length) {
      // 购物车数据
      carts = carts.map(function (m) {
        m.useBox = '0';
        m.num = '0';
        return m;
      });
      this.setData({
        carts: carts,
        numInputisabled: "false",
      });
      console.log(carts);
    } else {
      carts = carts.map(function (m) {
        m.useBox = '1';
        return m;
      });
      this.setData({
        carts: carts,
        numInputisabled: "true",
      });
      console.log(carts);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that =this;
    wx.setNavigationBarTitle({
      title: '选择智能箱子',
    })
    
    //页面初始化
    this.setData({
      orderAddressId: options.address_id
    })
    // 获取本地数据-用户信息
    wx.getStorage({
      key: 'userInfo',
      success: (json) => {
        console.log(json);
        this.setData({
          userInfo: json.data.userInfo
        })
      }
    });

    // 获取所有箱子类型
    const requestGetAllBoxType = wx.request({
      url: "https://boxapi.supergk.com/server/box/query_box_type",
      success:function(res){
        console.log("获取到所有箱子类型")
        console.log(res);
        if(res.data.code == 0){
          var _carts = res.data.data;
          for(var i =0; i<_carts.length; i++){
            _carts[i].num = "0"
          }
          that.setData({
            carts:res.data.data,
          })
        }
      }
    })
  },
  bindMinus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var useable = parseInt(this.data.carts[index].useBox);
    if (useable) {
      var num = this.data.carts[index].num;
      // 如果只有0件了，就不允许再减了
      if (num > 0) {
        num--;
      }
      // 只有大于0件的时候，才能normal状态，否则disable状态
      var minusStatus = num <= 0 ? 'disabled' : 'normal';
      // 购物车数据
      var carts = this.data.carts;
      carts[index].num = num;
      // 按钮可用状态
      var minusStatuses = this.data.minusStatuses;
      minusStatuses[index] = minusStatus;
      // 将数值与状态写回
      this.setData({
        carts: carts,
        minusStatuses: minusStatuses
      });
    }
  },
  bindPlus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var useable = parseInt(this.data.carts[index].useBox);
    if (useable) {
      var num = this.data.carts[index].num;
      // 自增
      num++;
      // 只有大于一件的时候，才能normal状态，否则disable状态
      var minusStatus = num <= 0 ? 'disabled' : 'normal';

      // 购物车数据
      var carts = this.data.carts;
      carts[index].num = num;
      // 按钮可用状态
      var minusStatuses = this.data.minusStatuses;
      minusStatuses[index] = minusStatus;
      // 将数值与状态写回
      this.setData({
        carts: carts,
        minusStatuses: minusStatuses
      });
    }
  },

  /* 输入框事件 */
  bindManual: function (e) {
    var num = e.detail.value;
    var index = parseInt(e.currentTarget.dataset.index);
    // 将数值与状态写回  
    var carts = this.data.carts;
    carts[index].num = num;
    this.setData({
      carts: carts,
    });
  },

  callCourier: function () {
    var that = this;
    var bigBoxNum;
    var smallBoxNum;
    var type = "1";
    var useable = parseInt(this.data.carts[0].useBox);
    if (useable) {
      bigBoxNum = parseInt(this.data.carts[0].num);
      smallBoxNum = parseInt(this.data.carts[1].num);

    } else {
      bigBoxNum = "0"
      smallBoxNum = "0"
    }
    console.log(bigBoxNum);
    console.log(smallBoxNum);
    console.log(this.data.userInfo);
    var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    // 呼叫快递员
    if (useable) { // （需要箱子）
      // 购物车数据
      var _carts = that.data.carts;
    var box_list_arr = [];
    var box_list_data = '[';
    
    _carts.forEach(function (item) {
      box_list_arr.push({ box_type_id: item.id, num: "1" })
    })
    for (var i = 0; i < _carts.length; i++) {
      box_list_data += '{"box_type_id":' + _carts[i].id + ',"num": ' + _carts[i].num + '},'
    }
    box_list_data = box_list_data.toString(0, box_list_data.Length - 1)
    box_list_data +=']'
    // var box_list_arr = '[{"box_type_id": "1","num": ' + bigBoxNum + '},{"box_type_id": "2","num": ' + smallBoxNum + '}]'
    console.log(box_list_data);
    console.log(bigBoxNum);
    
      const requestTask = wx.request({
        url: 'https://boxapi.supergk.com/server/user/call_courier',
        data: util.json2Form({
          uid: _uid,
          type: "1",
          address_id: this.data.orderAddressId,
          // box_list: [{ "box_type_id": "1", num: bigBoxNum }, { "box_type_id": "2", num: smallBoxNum }]
          box_list: box_list_arr
        }),
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res);
          if (res.data.code == "0") {
            // 存储我的快递召唤信息
            that.setData({
              orderStatus: res.data
            })
            // 存储我的快递召唤信息到本地
            wx.setStorage({
              key: 'orderStatus',
              data: {
                orderStatus: res.data,
              },
              success: function (e) {
                console.log("存储用户快递召唤信息成功")
                // util.showModel('召唤快递', error)
                wx.showModal({
                  title: '召唤快递',
                  content: res.data.msg,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: '../index/index',
                      })
                    }
                  }
                })
              },
            })
          }else{
            wx.showModal({
              title: '提示信息',
              content: res.data.msg,
              showCancel:false
            })
          }

        }
      })
    } else {// （不需要箱子）
      const requestTask = wx.request({
        url: 'https://boxapi.supergk.com/server/user/call_courier',
        data: util.json2Form({
          uid: _uid,
          type: "2",
          address_id: this.data.orderAddressId,
        }),
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res);
          if (res.data.code == "0") {
            // 存储我的快递召唤信息
            that.setData({
              orderStatus: res.data
            })
            // 存储我的快递召唤信息到本地
            wx.setStorage({
              key: 'orderStatus',
              data: {
                orderStatus: res.data,
              },
              success: function (e) {
                console.log("存储用户快递召唤信息成功")
                // util.showModel('召唤快递', error)
                wx.showModal({
                  title: '召唤快递',
                  content: res.data.msg,
                  showCancel:false,
                  success: function (res) {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: '../index/index',
                      })
                    }
                  }
                })
              },
            })
          }

        }
      })
    }
 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 跳转至首页
  movetoIndex: function () {
    wx.navigateTo({
      url: '../index/index'
    })
  }
})